package org.jeecg.modules.kuner.viporderbase.controller.api;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.Strings;
import org.jeecg.common.util.pay.wx.WxPayNotifyParser;
import org.jeecg.common.util.redisson.RedissonLockUtil;
import org.jeecg.modules.kuner.viporderbase.service.IKrVipOrderBaseService;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: Planifolia.Van
 * @Date: 2025/2/20 16:01
 */
@Slf4j
@RestController
@RequestMapping("/notify/order/payed")
public class VipOrderNotifyController {

    @Resource
    private WxPayNotifyParser wxPayNotifyParser;
    @Resource
    private RedissonLockUtil redissonLockUtil;
    @Resource
    private IKrVipOrderBaseService vipOrderBaseService;


    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/wx")
    @ApiOperation("微信支付成功")
    public Result<?> wx(HttpServletRequest request) {
        Result<?> result = wxPayNotifyParser.wxNotifyHandler(request);
        if (result.isSuccess()) {
            String orderNo = result.getResult().toString();
            return redissonLockUtil.tryLockAndExecute(orderNo, CommonConstant.MAX_WAIT_TIME, CommonConstant.MAX_LESS_TIME, TimeUnit.SECONDS, lockFlag -> {
                if (lockFlag) {
                    vipOrderBaseService.paySuccessLogic(orderNo);
                    return Result.OK(CommonConstant.WX_NOTIFY_STATUS_SUCCESS);
                } else {
                    log.error("orderNo:{}获取锁失败！", orderNo);
                    return Result.error(CommonConstant.WX_PAY_FAIL_RESPONSE_MSG);
                }
            });
        }
        return Result.error(CommonConstant.WX_PAY_FAIL_RESPONSE_MSG);
    }

    @GetMapping("/testNotify")
    public Result<?> testNotify(String password, String orderNo) {
        if (!"system2025.".equals(password)) {
            throw new JeecgBootException("密码错误!");
        }
        vipOrderBaseService.paySuccessLogic(orderNo);
        return Result.OK("回调成功！");
    }
}
